# -*- coding: utf-8 -*-
'''
@author: lowzoom
'''
from __future__ import division, print_function, unicode_literals
from _main_window import Ui_MainWindow
from btn_cfg import button_data_handler, key
from ui.boot_dialog import BootDialog
import PyQt4.QtCore as qtc
import PyQt4.QtGui as qt
import cfg
import main
import os

class MainWindow(qt.QMainWindow):
	'''
	程序主窗口
	'''
	def __init__(self):
		qt.QWidget.__init__(self, None)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)

		# 保存初始标题, 方便以后添加路径
		self.title = self.windowTitle()

		# 恢复上次关闭时的窗口状态
		self.restoreGeometry(cfg.pref.get(cfg.WINDOW_STATE, self.saveGeometry()))

		self.boot_dialog = BootDialog(self)
		self.connect(self.ui.boot_action, qtc.SIGNAL('triggered()'), self.boot_dialog.exec_)

		self.set_open_file()
		self.set_about_dialog()
		self.set_edits()
		self.set_button_box()

		qtc.QTimer.singleShot(0, self.init_run)

	def closeEvent(self, e):
		'''
		关闭时保存窗口状态
		'''
		cfg.pref[cfg.WINDOW_STATE] = self.saveGeometry()
		cfg.save()

	def init_run(self):
		'''
		初始运行检测
		'''
		class GamePathNotFound(Exception): pass

		try:
			if not cfg.pref[cfg.GAME_PATH]:
				raise GamePathNotFound('<p>这是您首次运行本程序<p>请先选择游戏主程序所在路径</p>')

			if not os.path.isdir(cfg.pref[cfg.GAME_PATH]):
				raise GamePathNotFound('<p>游戏目录有变动<p>请重新选择游戏主程序所在路径</p>')

		except GamePathNotFound as ex:
			qt.QMessageBox.information(self, '提示', unicode(ex))

			# 游戏主程序路径
			exe_path = str(qt.QFileDialog.getOpenFileName(
				parent=self,
				caption='选择游戏主程序',
				filter='fifa.exe'))

			if not exe_path:
				self.close()
				return

			# 获取游戏目录路径
			cfg.set_game_path(os.path.dirname(os.path.normpath(exe_path)))
			cfg.save()

		# 检测通过后读取按钮配置
		self.load_button_data()

	def load_button_data(self):
		'''
		读取按键设置并显示
		'''
		button_data_handler.load()

		# 将键位设置显示到输入框
		for btn, edit in self.edit_map.iteritems():
			edit.setText(button_data_handler.key_map[btn])

	def save_button_data(self):
		'''
		保存按键设置到文件
		'''
		button_data_handler.save()
		qt.QMessageBox.information(self, '提示', '保存完成')

	def set_button_box(self):
		'''
		设置底部两个按扭的外观和事件
		'''
		reset_btn = self.ui.buttonBox.button(qt.QDialogButtonBox.Reset)
		reset_btn.setFocusPolicy(qtc.Qt.NoFocus)
		reset_btn.setText('重置')
		self.connect(reset_btn, qtc.SIGNAL('clicked()'), self.load_button_data)

		save_btn = self.ui.buttonBox.button(qt.QDialogButtonBox.Save)
		save_btn.setText('保存')
		self.connect(save_btn, qtc.SIGNAL('clicked()'), self.save_button_data)

	def set_open_file(self):
		'''
		设置打开文件动作
		'''
		def _open():
			'''
			弹出文件选择框, 打开配置文件
			'''
			data_file_path = str(qt.QFileDialog.getOpenFileName(
				parent=self,
				caption="选择配置文件",
				directory=os.path.dirname(button_data_handler.path),
				filter=';;'.join((button_data_handler.file_name,
								'所有文件 (*.*)'))))

			if not data_file_path:
				return

			button_data_handler.path = os.path.normpath(data_file_path)
			self.load_button_data()

			self.setWindowTitle('{app} [{path}]'.format(
				app=self.title,
				path=button_data_handler.path))

		self.connect(self.ui.open_action, qtc.SIGNAL('triggered()'), _open)

	def set_edits(self):
		'''
		设置输入框的动作
		'''
		# 按键对应的输入框
		self.edit_map = {
			'VB_AI_LT': self.ui.lt_edit,
			'VB_AI_LB': self.ui.lb_edit,
			'VB_AI_BACK': self.ui.back_edit,
			'VB_AI_LS_UP': self.ui.ls_up_edit,
			'VB_AI_LS_LEFT': self.ui.ls_left_edit,
			'VB_AI_LS_DOWN': self.ui.ls_down_edit,
			'VB_AI_LS_RIGHT': self.ui.ls_right_edit,
			'VB_AI_LDPAD_UP': self.ui.ldpad_up_edit,
			'VB_AI_LDPAD_LEFT': self.ui.ldpad_left_edit,
			'VB_AI_LDPAD_DOWN': self.ui.ldpad_down_edit,
			'VB_AI_LDPAD_RIGHT': self.ui.ldpad_right_edit,
			'VB_AI_L3': self.ui.l3_edit,
			'VB_AI_RT': self.ui.rt_edit,
			'VB_AI_RB': self.ui.rb_edit,
			'VB_AI_START': self.ui.start_edit,
			'VB_AI_Y': self.ui.y_edit,
			'VB_AI_B': self.ui.b_edit,
			'VB_AI_A': self.ui.a_edit,
			'VB_AI_X': self.ui.x_edit,
			'VB_AI_RS_UP': self.ui.rs_up_edit,
			'VB_AI_RS_RIGHT': self.ui.rs_right_edit,
			'VB_AI_RS_DOWN': self.ui.rs_down_edit,
			'VB_AI_RS_LEFT': self.ui.rs_left_edit,
			'VB_AI_R3': self.ui.r3_edit
		}

		# 输入框对应的按键
		for btn, edit in self.edit_map.iteritems():
			assert not hasattr(edit, 'cor_btn'), '和qt的属性撞车了, 您的RP需要充值'
			edit.cor_btn = [btn]

		self.ui.ls_right_edit.cor_btn.append('VB_FE_LS_RIGHT')
		self.ui.ls_up_edit.cor_btn.append('VB_FE_LS_UP')
		self.ui.ls_left_edit.cor_btn.append('VB_FE_LS_LEFT')
		self.ui.ls_down_edit.cor_btn.append('VB_FE_LS_DOWN')
		self.ui.rs_right_edit.cor_btn.append('VB_FE_RS_RIGHT')
		self.ui.rs_up_edit.cor_btn.append('VB_FE_RS_UP')
		self.ui.rs_left_edit.cor_btn.append('VB_FE_RS_LEFT')
		self.ui.rs_down_edit.cor_btn.append('VB_FE_RS_DOWN')
		self.ui.x_edit.cor_btn.append('VB_FE_X')
		self.ui.y_edit.cor_btn.append('VB_FE_Y')
		self.ui.lb_edit.cor_btn.append('VB_FE_LB')
		self.ui.rb_edit.cor_btn.append('VB_FE_RB')
		self.ui.lt_edit.cor_btn.append('VB_FE_LT')
		self.ui.rt_edit.cor_btn.append('VB_FE_RT')
		self.ui.l3_edit.cor_btn.append('VB_FE_L3')
		self.ui.r3_edit.cor_btn.append('VB_FE_R3')

		# 让文本框可以设置按键
		def accept_key(edit):
			def handler(e):
				if e.type() == qtc.QEvent.KeyPress:
					scan_code = e.nativeScanCode()
					if scan_code in key.name:
						key_name = key.name[scan_code]
						edit.setText(key_name)
						button_data_handler.set_key(edit.cor_btn, key_name)

						if self.ui.continuous_set_cbox.isChecked():
							edit.focusNextChild()
					else:
						qt.QMessageBox.critical(self, '错误', '未知按键码: {code}'.format(code=hex(int(scan_code))))
					return True
				return qt.QWidget.event(edit, e) # handler end
			return handler # accept_key end

		for edit in self.edit_map.itervalues():
			edit.event = accept_key(edit)
			edit.setContextMenuPolicy(qtc.Qt.NoContextMenu)

	def set_about_dialog(self):
		'''
		设置"关于"的动作
		'''
		def show():
			'''
			显示“关于”对话框
			'''
			qt.QMessageBox.about(self, '关于',
				"""<b>{app_name}</b> v {ver}
				<p>用于设置 FIFA 12 按键的小工具，仅适用于键盘。
				<p>lowZoom &copy; Powered by PyQt</p>""".format(
					app_name=qt.QApplication.applicationName(),
				  ver=main.__version__))

		# 弹出关于对话框
		self.connect(self.ui.about_action, qtc.SIGNAL('triggered()'), show)
